package com.mb.app.appused.core;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.mb.app.appused.adapter.ListItemAdapter;
import com.mb.app.appused.greendao.SimpleDataUtil;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.widget.Toast;

public class AppInfoManager {

	Context context;
	long wait = 1000;
	Handler mHandler;
	String current = "";
	String last = "";
	Runnable runnable;
	SimpleDataUtil data;

	public AppInfoManager(Context context) {
		this.context = context;
		data = new SimpleDataUtil();
		data.setupDatabase(context, ListItemAdapter.DataBaseName);
		mHandler = new Handler();
		setRun(true);

	}

	public void setRun(Boolean run) {
		if (mHandler == null)
			mHandler = new Handler();

		if (runnable == null) {
			runnable = new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mHandler.postDelayed(this, wait);
					action();
				}
			};
			mHandler.postDelayed(runnable, wait);
		}

		if (!run && mHandler != null && runnable != null)
			mHandler.removeCallbacks(runnable);
	}

	void action() {

		current = getApp();
		if (current.compareTo(last) != 0) {
			data.insert(context, current, getTime(), "开启");

			if (last != null && last.length() > 0) {
				data.insert(context, last, getTime(), "关闭");
			}
		}

		last = current;
	}

	@SuppressLint("SimpleDateFormat")
	String getTime() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
		// 获取当前时间
		Date date = new Date(System.currentTimeMillis());
		return simpleDateFormat.format(date);
	}

	public String getApp() {
		if (context == null)
			return "";
		String pn = "";

		ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		if (Build.VERSION.SDK_INT > 20) {
			pn = mActivityManager.getRunningAppProcesses().get(0).processName;
		} else {
			pn = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
		}
		return pn;
	}
}
